<?php
//No direct access
defined('_JEXEC') or die('Restricted access');

jimport('joomla.application.component.controller');

class OwnserviceControllerTransaction extends JController
{
	/**
	 * Controller construct
	*/
	function __construct(){
		parent::__construct();
	}

	/**
	 * Method to get transaction details
	 *
	 * @return void
	 * @since 1.0
	*/
	function detail() {

		global $mainframe;

		// Initialise variables
		$user		= & JFactory::getUser();
		$ownuser	= & Ownservice::getUser();

		if($user->gid < 25) {
			$canView	= Ownservice::checkAccess('transaction', 'view', 'transaction', 'all');
			if (!$canView) {
				JError::raiseWarning(500, JText::_('ALERTNOTAUTH') );
				$mainframe->redirect(JRoute::_('index.php?option=com_ownservice'));
			}
		}

		// Create the view
		$view = & $this->getView('transaction', 'html');

		// Get/Create the model
		$model = & $this->getModel('Transaction');

		// Push the model into the view (as default)
		$view->setModel($model, true);

		// Set the layout
		$view->setLayout('default');

		// Display the view
		$view->display();
	}

	/**
	 * Method to get form  edit transaction
	 *
	 * @return void
	 * @since 1.0
	 */
	function edit(){

		global $mainframe;

		// Check for request forgeries
		JRequest::checkToken( 'request' ) or jexit( 'Invalid Token' );

		// Initialise variables
		$user		= & JFactory::getUser();
		$ownuser	= & Ownservice::getUser();

		if($user->gid < 25) {
			$canEdit	= Ownservice::checkAccess('transaction', 'edit', 'transaction', 'all');
			if (!$canEdit) {
				JError::raiseWarning(500, JText::_('ALERTNOTAUTH') );
				$mainframe->redirect(JRoute::_('index.php?option=com_ownservice'));
			}
		}

		// Create the view
		$view = & $this->getView('transaction', 'html');

		// Get/Create the model
		$model = & $this->getModel('Transaction');

		// Push the model into the view (as default)
		$view->setModel($model, true);

		// Set the layout
		$view->setLayout('form');

		// Display the view
		$view->display();

	}

	/**
	* Method to add an custom account
	*
	* @access	public
	* @since	1.0
	*/
	function add() {

		global $mainframe;

		// Initialise variables
		$user		= & JFactory::getUser();
		$ownuser	= & Ownservice::getUser();

		if($user->gid < 25) {
			$canAdd		= Ownservice::checkAccess('transaction', 'add', 'transaction', 'all');
			if (!$canAdd) {
				JError::raiseWarning(500, JText::_('ALERTNOTAUTH') );
				$mainframe->redirect(JRoute::_('index.php?option=com_ownservice'));
			}
		}

		// Create the view
		$view = & $this->getView('transaction', 'html');

		// Get/Create the model
		$model = & $this->getModel('Transaction');

		// Push the model into the view (as default)
		$view->setModel($model, true);

		// Set the layout
		$view->setLayout('form');

		// Display the view
		$view->display();
	}

	/**
	* Method to print transaction details
	*
	* @access	public
	* @since	1.0
	*/
	function printDetails() {

		global $mainframe;

		// Initialise variables
		$user		= & JFactory::getUser();
		$ownuser	= & Ownservice::getUser();

		if($user->gid < 25) {
			$canView		= Ownservice::checkAccess('transaction', 'view', 'transaction', 'all');
			if (!$canView) {
				JError::raiseWarning(500, JText::_('ALERTNOTAUTH') );
				$mainframe->redirect(JRoute::_('index.php?option=com_ownservice'));
			}
		}

		// Create the view
		$view = & $this->getView('transaction', 'html');

		// Get/Create the model
		$model = & $this->getModel('Transaction');

		// Push the model into the view (as default)
		$view->setModel($model, true);

		// Set the layout
		$view->setLayout('print');

		// Display the view
		$view->display();
	}

	/**
	* Method to print transaction invoice
	*
	* @access	public
	* @since	1.0
	*/
	function printReceipt() {

		global $mainframe;

		// Initialise variables
		$user		= & JFactory::getUser();
		$ownuser	= & Ownservice::getUser();

		if($user->gid < 25) {
			$canView		= Ownservice::checkAccess('transaction', 'view', 'transaction', 'all');
			if (!$canView) {
				
				JError::raiseWarning(500, JText::_('ALERTNOTAUTH') );
				$mainframe->redirect(JRoute::_('index.php?option=com_ownservice'));
			}
		}

		// Create the view
		$view = & $this->getView('transaction', 'html');

		// Get/Create the model
		$model = & $this->getModel('Transaction');

		// Push the model into the view (as default)
		$view->setModel($model, true);

		// Set the layout
		$view->setLayout('receipt');

		// Display the view
		$view->display();
	}

	/**
	 * Logic to save transaction
	 * 
	 * @access public
	 * @return void
	*/
	function save(){

		//Check for request forgeries
		JRequest::checkToken() or jexit('Invalid Token');

		$user	= & JFactory::getUser();
		$app	= &	JFactory::getApplication();
		$db		= & JFactory::getDBO();

		// Get vars
		$post = JRequest::get( 'post' );

		$model = $this->getModel('Transaction');

		if($model->canTransfer($post['user_id'])) {
			if($model->store($post)) {
				$msg = JText::_('OWNSERVICE_TRANSFER_SAVED');
			}else {
				$type = 'error';
				$msg = JText::_('OWNSERVICE_ERROR_SAVING_TRANSFER');
			}

			$link = JRoute::_('index.php?option=com_ownservice&amp;view=transaction&amp;id='.$model->get('id'));
		} else {
			$type	= 'error';
			$msg	= JText::_('OWNSERVICE_EXPIRE');

			$link = JRoute::_('index.php?option=com_ownservice&amp;controller=transaction&amp;task=add');
		}

		$this->setRedirect($link, $msg, $type);
	}

	/**
	 * Method to get customer transfers
	 *
	 * @return void
	 * @since 1.0
	 */
	 function customertransfers(){

		global $mainframe;

		// Initialise variables
		$user			= & JFactory::getUser();
		$ownuser	= & Ownservice::getUser();

		if($user->gid < 25) {
			$canCustomerTransfers= Ownservice::checkAccess('transaction', 'customer', 'transaction', 'all');
			if ( !$canCustomerTransfers ) {
				JError::raiseWarning(500, JText::_('ALERTNOTAUTH') );
				$mainframe->redirect(JRoute::_('index.php?option=com_ownservice'));
			}
		}

		// Create the view
		$view = & $this->getView('transactions', 'html');

		// Get/Create the model
		$model = & $this->getModel('Transactions');

		// Push the model into the view (as default)
		$view->setModel($model, true);

		// Set the layout
		$view->setLayout('customertransfers');

		// Display the view
		$view->display();
	 }

	/**
	 * Method to get form  approval request
	 *
	 * @return void
	 * @since 1.0
	 */
	function paidtransactions(){

		global $mainframe;

		// Initialise variables
		$user		= & JFactory::getUser();
		$ownuser	= & Ownservice::getUser();

		if($user->gid < 25) {
			$canRequestApproval= Ownservice::checkAccess('transaction', 'approval', 'transaction', 'all');

			if ( !$canRequestApproval ) {
				JError::raiseWarning(500, JText::_('ALERTNOTAUTH') );
				$mainframe->redirect(JRoute::_('index.php?option=com_ownservice'));
			}
		}

		// Create the view
		$view = & $this->getView('transactions', 'html');

		// Get/Create the model
		$model = & $this->getModel('Transactions');

		// Push the model into the view (as default)
		$view->setModel($model, true);

		// Set the layout
		$view->setLayout('paidtransactions');

		// Display the view
		$view->display();
	}

	/**
	 * Method to get request approval
	 *
	 * @return void
	 * @since 1.0
	 */
	function requestapproval() {

		global $mainframe;

		// Initialise variables
		$user		= & JFactory::getUser();
		$ownuser	= & Ownservice::getUser();
		$gid		= $user->gid;

		if($gid < 25) {
			$canTransfer= Ownservice::checkAccess('transaction', 'transfer', 'transaction', 'all');
			if ( !$canTransfer ) {
				JError::raiseWarning(500, JText::_('ALERTNOTAUTH') );
				$mainframe->redirect(JRoute::_('index.php?option=com_ownservice'));
			}
		}

		// Create the view
		$view = & $this->getView('transactions', 'html');

		// Get/Create the model
		$model = & $this->getModel('Transactions');

		// Push the model into the view (as default)
		$view->setModel($model, true);

		// Set the layout
		$view->setLayout('requestapproval');

		// Display the view
		$view->display();
	}
	
	/**
	 * Method to get request approval corrected
	 *
	 * @return void
	 * @since 1.0
	 */
	function requestapprovalcorrected()
	{
		global $mainframe;

		// Initialise variables
		$user		= & JFactory::getUser();
		$ownuser	= & Ownservice::getUser();
		$gid		= $user->gid;

		if($gid < 25) {
			$canTransfer= Ownservice::checkAccess('transaction', 'transfer', 'transaction', 'all');
			if ( !$canTransfer ) {
				JError::raiseWarning(500, JText::_('ALERTNOTAUTH') );
				$mainframe->redirect(JRoute::_('index.php?option=com_ownservice'));
			}
		}

		// Create the view
		$view = & $this->getView('transactions', 'html');

		// Get/Create the model
		$model = & $this->getModel('Transactions');

		// Push the model into the view (as default)
		$view->setModel($model, true);

		// Set the layout
		$view->setLayout('requestapprovalcorrected');

		// Display the view
		$view->display();
	}

	/**
	 * Method get failed transactions
	 *
	 * @return void
	 * @since 1.0
	*/
	function failedtransactions()
	{
		global $mainframe;

		// Initialise variables
		$user			= & JFactory::getUser();
		$ownuser	= & Ownservice::getUser();
		$gid			= $user->gid;

		if($gid < 25) {
			$canF= Ownservice::checkAccess('transaction', 'failed', 'transaction', 'all');
			if ( !$canF ) {
				JError::raiseWarning(500, JText::_('ALERTNOTAUTH') );
				$mainframe->redirect(JRoute::_('index.php?option=com_ownservice'));
			}
		}

		// Create the view
		$view = & $this->getView('transactions', 'html');

		// Get/Create the model
		$model = & $this->getModel('Transactions');

		// Push the model into the view (as default)
		$view->setModel($model, true);

		// Set the layout
		$view->setLayout('failedtransactions');

		// Display the view
		$view->display();
	}

	/**
	 * Method get cancelled transactions
	 *
	 * @return void
	 * @since 1.0
	*/
	function cancelledtransactions()
	{
		global $mainframe;

		// Initialise variables
		$user			= & JFactory::getUser();
		$ownuser	= & Ownservice::getUser();
		$gid			= $user->gid;

		if($gid < 25) {
			$canC= Ownservice::checkAccess('transaction', 'cancelled', 'transaction', 'all');
			if ( !$canC ) {
				JError::raiseWarning(500, JText::_('ALERTNOTAUTH') );
				$mainframe->redirect(JRoute::_('index.php?option=com_ownservice'));
			}
		}

		// Create the view
		$view = & $this->getView('transactions', 'html');

		// Get/Create the model
		$model = & $this->getModel('Transactions');

		// Push the model into the view (as default)
		$view->setModel($model, true);

		// Set the layout
		$view->setLayout('cancelledtransactions');

		// Display the view
		$view->display();
	}
	
	/**
	 * Method get corrected transactions
	 *
	 * @return void
	 * @since 1.0
	*/
	function correctedtransactions()
	{
		global $mainframe;

		// Initialise variables
		$user		= & JFactory::getUser();
		$ownuser	= & Ownservice::getUser();
		$gid		= $user->gid;

		if($gid < 25) {
			$canC= Ownservice::checkAccess('transaction', 'corrected', 'transaction', 'all');
			if ( !$canC ) {
				JError::raiseWarning(500, JText::_('ALERTNOTAUTH') );
				$mainframe->redirect(JRoute::_('index.php?option=com_ownservice'));
			}
		}

		// Create the view
		$view = & $this->getView('transactions', 'html');

		// Get/Create the model
		$model = & $this->getModel('Transactions');

		// Push the model into the view (as default)
		$view->setModel($model, true);

		// Set the layout
		$view->setLayout('correctedtransactions');

		// Display the view
		$view->display();
	}

	/**
	 * Method get transferring transactions
	 *
	 * @return void
	 * @since 1.0
	*/
	function transferring()
	{
		global $mainframe;

		// Initialise variables
		$user		= & JFactory::getUser();
		$ownuser= & Ownservice::getUser();
		$gid		= $user->gid;

		if($gid < 25) {
			$canTR= Ownservice::checkAccess('transaction', 'transferring', 'transaction', 'all');
			if ( !$canTR ) {
				JError::raiseWarning(500, JText::_('ALERTNOTAUTH') );
				$mainframe->redirect(JRoute::_('index.php?option=com_ownservice'));
			}
		}

		// Create the view
		$view = & $this->getView('transactions', 'html');

		// Get/Create the model
		$model = & $this->getModel('Transactions');

		// Push the model into the view (as default)
		$view->setModel($model, true);

		// Set the layout
		$view->setLayout('transferring');

		// Display the view
		$view->display();
	}

	/**
	 * Method get account receive
	 *
	 * @return string
	 * @since 1.5
	*/
	function getAccounts(){

		// Check for request forgeries
		JRequest::checkToken('request') or jexit( 'Invalid Token' );
		
		$model = & $this->getModel('Transaction');

		//Get var
		$id = JRequest::getVar('id', 0, 'post', 'int');

		//Get data form the model
		$banks	= $model->getAccounts($id);

		$profile	= $model->getUser($id);
		
		//build transfer to select list
		//echo OwnserviceHelper::buildbanksselect($banks, 'account','',true, 'class="inputbox" style="width:250px;"');
		echo '<table>
				<tbody>
					<tr>
						<td style="margin: 0; padding: 0;">
							<div id="accountno">'.OwnserviceHelper::buildbanksselect($banks, 'account','',true, 'class="inputbox" style="width:250px;"').'</div>
						</td>
						<td>
							<div class="button2-left">
								<div class="blank">
									<a href="'.JRoute::_('index.php?option=com_ownservice&controller=member&task=acadd&mid='.$profile->id).'" title="'.JText::_('OWNSERVICE_ADD_RECEIVER').'">'.JText::_('OWNSERVICE_ADD_RECEIVER').'</a>
								</div>
							</div>
						</td>
					</tr>
				</tbody>
			</table>';
		
		exit();
	}

	/**
	 * Method to get currency list
	 *
	 * @return string
	 * @since 1.5
	*/
	function getCurrency() {
			
		// Check for request forgeries
		JRequest::checkToken('request') or jexit( 'Invalid Token' );
		
		$user 		=& JFactory::getUser();
		
		$id			= JRequest::getVar('id', 0, 'post', 'int');
		
		//get Data from the model
		$model 		= $this->getModel('Transaction');
		$profile 	= $model->getUser($id);
		$currencies = $model->getCurrencies($profile->branch_id);
		
		//build currency select list
		echo $currency	= OwnserviceHelper::buildcurrenciesselect($currencies, 'rate_id',$profile->rate_id,true, 'class="inputbox required" style="width:250px;"');

		exit();
	}
	
	/**
	 * Method to get exchange money rate
	 *
	 * @return string
	 * @since 1.5
	*/
	function getExchange() {
			
		// Check for request forgeries
		JRequest::checkToken('request') or jexit( 'Invalid Token' );
		
		//Initialise
		$user 		= & JFactory::getUser();
		$ownuser	= & Ownservice::getUser();
		$db			= & JFactory::getDbo();
		
		//get vars
		$id			= & JRequest::getVar('id', 0 , 'post', 'int');
		$rate_id 	= & JRequest::getVar('rate_id', 0, 'post', 'int');
		
		$query = ' SELECT p.branch_id '
				.' FROM #__users AS u '
				.' LEFT JOIN #__ownservice_users AS p ON p.user_id=u.id '
				.' WHERE u.id='.$id;
				
		$db->setQuery($query);
		$branch_id = $db->loadResult();
		
		$query = ' SELECT r. *, c.code '
				.' FROM #__ownservice_exchangerates AS r '
				.' LEFT JOIN #__ownservice_currencies AS c ON c.id=r.currency_id '
				.' WHERE r.id='.$rate_id
				.' AND r.branch_id='.$branch_id
				;
		
		$db->setQuery($query);
		$row = $db->loadObject();
		
		if(!is_object($row)){
			$row = new stdClass();
			$row->rate = null;
			$row->code = null;
		}
		
		//header('Content-type: application/json');
		@ob_end_clean();
		header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
		header("Cache-Control: no-cache");
		header("Pragma: no-cache");
		
		echo json_encode($row);
		
		exit();
	}

	/**
	 * Method get total exchange money
	 *
	 * @return string
	 * @since 1.0
	*/
	function getTotal() {

		//Check for request forgeries
		JRequest::checkToken() or jexit('Invalid Token');

		$db = & JFactory::getDBO();

		$post = JRequest::get( 'post' );
		
		//get branch ID
		$query = ' SELECT p.branch_id FROM #__users AS u '
				.' LEFT JOIN #__ownservice_users AS p ON p.user_id=u.id '
				.' WHERE u.id='.$post['user_id'];
				
		$db->setQuery($query);
		$branch_id = $db->loadResult();
		
		//get rate ID
		$query = ' SELECT r.id  '
				.' FROM #__ownservice_exchangerates AS r '
				.' WHERE r.id='.$post['rate_id']
				.' AND r.branch_id='.$branch_id;
		
		$db->setQuery($query);
		$rate_id = $db->loadResult();
		
		//get fee
		$query = "SELECT fee FROM `#__ownservice_fees` WHERE `rate_id` =".$rate_id." AND `type` = 'fee' AND `from` <=".$post['amount']." AND `to` >=".$post['amount'];
		$db->setQuery($query);
		$fee = $db->loadResult();

		$fee = $fee?$fee:'0.00';
		
		//get destination fee
		$query = "SELECT fee FROM `#__ownservice_fees` WHERE `rate_id` =".$rate_id." AND `type` = 'destinationfee' AND `from` <=".$post['amount']." AND `to` >=".$post['amount'];
		$db->setQuery($query);
		$bankfee = $db->loadResult();
		
		$bankfee = $bankfee?$bankfee:'0.00';

		$total = round( ( ($post['amount'] * ($post['rate'] + $post['extrarate']) ) - ($bankfee + $post['extrabfee']) ), 2);
		
		header('Cache-Control: no-cache, must-revalidate');
		header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
		header('Content-type: application/json');

		echo "{'total': '".$total."', 'fee': '".$fee."', 'bankfee':'".$bankfee."'}";
		exit();
	}

	/**
	 * Method get amount transfer money
	 *
	 * @return string
	 * @since 1.0
	 */
	function getTransfer() {

		//Check for request forgeries
		JRequest::checkToken() or jexit('Invalid Token');

		$db 	= & JFactory::getDBO();

		$post 	= JRequest::get( 'post' );

		//Get branch ID
		$query 	= ' SELECT p.branch_id FROM #__users AS u '
				.' LEFT JOIN #__ownservice_users AS p ON p.user_id=u.id '
				.' WHERE u.id='.$post['user_id'];
				
		$db->setQuery($query);
		$branch_id = $db->loadResult();
		
		//Get rate ID	
		$query = ' SELECT r.id '
				.' FROM #__ownservice_exchangerates AS r '
				.' WHERE r.id='.$post['rate_id']
				.' AND r.branch_id='.$branch_id
				;
				
		$db->setQuery($query);
		$rate_id 		= $db->loadResult();
		
		$amount 		= round(($post['sumtotal'] / ($post['rate'] + $post['extrarate'])), 2);
		
		$num			= $this->calAmount($amount);
		
		$amount			= $amount+('0.0'.$num);
		
		//get fee
		$query = "SELECT fee FROM `#__ownservice_fees` WHERE `rate_id` =".$rate_id." AND `type` = 'fee' AND `from` <=".$amount." AND `to` >=".$amount;
		$db->setQuery($query);
		$fee = $db->loadResult();

		$fee = $fee?$fee:'0.00';
		
		//get destination fee
		$query = "SELECT fee FROM `#__ownservice_fees` WHERE `rate_id` =".$rate_id." AND `type` = 'destinationfee' AND `from` <=".$amount." AND `to` >=".$amount;
		$db->setQuery($query);
		$bankfee 	= $db->loadResult();
		
		$bankfee 	= $bankfee?$bankfee:'0.00';

		$amount 	= round((($post['sumtotal']+$bankfee) / ($post['rate'] + $post['extrarate'])), 2); //16/01/56

		$num		= $this->calAmount($amount);
		
		$amount		= $amount+('0.0'.$num);

		header('Cache-Control: no-cache, must-revalidate');
		header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
		header('Content-type: application/json');

		echo "{'amount': '".$amount."', 'fee': '".$fee."', 'bankfee':'".$bankfee."'}";
		exit();
	}

	function calAmount($amount)
	{
		list($a1, $a2)	= explode('.', $amount);
		$temp 			= substr($a2, -1);

		if($temp > 0 && $temp < 5){
			$num = 5 - $temp;
		} elseif($temp > 5){
			$num = 10 - $temp; 
		}else{
			$num = 0;
		}

		return $num;
	}
	
	/**
	 * Method to get other detail
	 *
	 * @return string 
	 * @since 1.0
	*/
	function getotherdetail()
	{
		// Check for request forgeries
		JRequest::checkToken('request') or jexit( 'Invalid Token' );
		
		$id			= JRequest::getVar('id', 0, 'post', 'int');
		$account  = JRequest::getVar('account', '', 'post', 'string');
		
		//get Data from the model
		$model 	= $this->getModel('Transaction');
		$profile 	= $model->getUser($id);
		$account	= $model->getAccount($account);
		
		if($account->birthday == '0000-00-00') {
			$birthday = null;
		} else {
			$birthday = $account->birthday;
		}
		
		$html ='<table width="100%" cellpadding="1" cellspacing="1">';
		$html .='<tr>';
			$html .='<td class="key">'.JText::_('OWNSERVICE_OCCUPATION').'</td>';
			$html .= '<td><input type="text"  name="occupation" id="occupation" value="'.$profile->occupation.'" /></td>';
		$html .= '</tr>';
		$html .='<tr>';
			$html .='<td class="key">'.JText::_('OWNSERVICE_BIRTHDAY_RECEIVER').'</td>';
			$html .= '<td>'.JHTML::_('calendar', $birthday, 'birthday', 'birthday', '%Y-%m-%d',array('class'=>'inputbox')).'</td>';
		$html .= '</tr>';
		$html .='</table>';
		
		echo $html;
		
		exit();
	}

	/**
	 * Logic to delete transaction
	 *
	 * @access public
	 * @return void
	 * @since 1.0
	*/
	function delete() {

		global $mainframe;

		//Check for request forgeries
		JRequest::checkToken() or jexit('Invalid Token');

		//Initialise variables
		$user		 = & JFactory::getUser();

		$id			= JRequest::getVar( 'id', 0, 'post', 'int' );
		$cid		= JRequest::getVar( 'cid', 0, 'post', 'array' );
		
		if ($return = JRequest::getVar('return', '', 'method', 'base64')) {
			$return = base64_decode($return);
			if (!JURI::isInternal($return)) {
				$return = '';
			}
		}

		$id			= is_array($cid)?$cid:$id;

		$model 		= $this->getModel('Transactions');

		if($user->gid < 25) {
			$canDelete		= Ownservice::checkAccess('transaction', 'delete', 'transaction', 'all');

			if ( !$canDelete ) {
				
				JError::raiseWarning(500, JText::_('ALERTNOTAUTH') );
				$mainframe->redirect(JRoute::_('index.php?option=com_ownservice'));
			}
		}

		if ($id < 1) {
			$msg = '';
			JError::raiseWarning(500, JText::_( 'OWNSERVICE_SELECT_ITEM_DELETED' ) );

		} else {

			if (!$model->delete($id)) {
				JError::raiseError(500, JText::_( 'OWNSERVICE_TRANSACTION_FAILED' ));
			}
			
			$msg = JText::_( 'OWNSERVICE_TRANSACTION_DELETED' );
		}
		
		// Redirect if the return url is not registration or login
		if ( ! $return ) {
			$this->setRedirect( 'index.php?option=com_ownservice&view=transactions', $msg );
		} else {
			$this->setRedirect( $return, $msg );
		}
	}

	/**
	 * logic for cancel an action
	 *
	 * @access public
	 * @return void
	 * @since 1.0
	 */
	function cancel()
	{
		// Check for request forgeries
		JRequest::checkToken() or jexit( 'Invalid Token' );
		
		$app =& JFactory::getApplication();
		
		$link = JRoute::_('index.php?option=com_ownservice&view=transactions');

		$this->setRedirect( $link );
	}

	/**
	 * Logic to submit transaction to request approval
	 *
	 * @access public
	 * @return void
	 * @since 1.5
	 */
	function approval() {

		global $mainframe, $option;

		//Initialise variables
		$user		= & JFactory::getUser();
		$ownuser	= & Ownservice::getUser();
		$db			= & JFactory::getDBO();

		//set vars
		$gid		= $user->gid;

		if($gid < 25) {
			$canRequestApproval	= Ownservice::checkAccess('transaction', 'approval', 'transaction', 'all');
			if (!$canRequestApproval) {
				JError::raiseWarning(500, JText::_('ALERTNOTAUTH') );
				$mainframe->redirect(JRoute::_('index.php?option=com_ownservice'));
			}
		}

		//get Vars
		$cid	= JRequest::getVar( 'cid', array(), 'post', 'array' );

		if (!is_array( $cid ) || count( $cid ) < 1) {
			$msg = '';
			JError::raiseWarning(500, JText::_( 'OWNSERVICE_SELECT_REQUEST_APPROVEL' ) );
		}

		$model = $this->getModel('Transactions');

		if(!$model->updateRequestApproval($cid)){
			$msg = $model->getError();
		} else {
			$msg = count($cid) . ' ' .JText::_( 'OWNSERVICE_REQUEST_APPROVAL' );			
		}

		$mainframe->enqueueMessage($msg);

		return $this->execute('paidtransactions');
	}

	/**
	 * Logic to submit transaction to request approval corrected
	 *
	 * @access public
	 * @return void
	 * @since 1.5
	 */   
	function approvalcorrected()
	{
		global $mainframe, $option;

		//Initialise variables
		$user		= & JFactory::getUser();
		$ownuser	= & Ownservice::getUser();
		$db			= & JFactory::getDBO();

		//set vars
		$gid		= $user->gid;

		if($gid < 25) {
			$canRequestApproval	= Ownservice::checkAccess('transaction', 'corrected', 'transaction', 'all');
			if (!$canRequestApproval) {
				JError::raiseWarning(500, JText::_('ALERTNOTAUTH') );
				$mainframe->redirect(JRoute::_('index.php?option=com_ownservice'));
			}
		}

		//get Vars
		$cid	= JRequest::getVar( 'cid', array(), 'post', 'array' );

		if (!is_array( $cid ) || count( $cid ) < 1) {
			$msg = '';
			JError::raiseWarning(500, JText::_( 'OWNSERVICE_SELECT_REQUEST_APPROVEL' ) );
		}

		$model = $this->getModel('Transactions');

		if(!$model->updateRequestApprovalCorrected($cid)){
			$msg = $model->getError();
		} else {
			$msg = count($cid) . ' ' .JText::_( 'OWNSERVICE_REQUEST_APPROVAL_CORRECTED' );			
		}

		$mainframe->enqueueMessage($msg);

		return $this->execute('correctedtransactions');
	}

	/**
	 * Logic to resubmit transaction
	 *
	 * @access public
	 * @return void
	 * @since 1.5
	 */
	function resubmit()
	{
		global $mainframe;
		
		//Initialise variables
		$user		= &JFactory::getUser();
		$ownuser	= & Ownservice::getUser();
		$db			= & JFactory::getDBO();
		
		//get vars
		$gid		= $user->gid;
		
		if($gid < 25) {
			$canF= Ownservice::checkAccess('transaction', 'failed', 'transaction', 'all');
			if ( !$canF ) {
				JError::raiseWarning(500, JText::_('ALERTNOTAUTH') );
				$mainframe->redirect(JRoute::_('index.php?option=com_ownservice'));
			}
		}

		//get Vars
		$cid	= JRequest::getVar( 'cid', array(), 'post', 'array' );

		if (!is_array( $cid ) || count( $cid ) < 1) {
			$msg = '';
			JError::raiseWarning(500, JText::_( 'OWNSERVICE_SELECT_FAILED_TRANSACTIONS' ) );
		}

		$model = $this->getModel('Transactions');

		if(!$model->updateCorrected($cid)){
			$msg = $model->getError();
		} else {
			$msg = count($cid) . ' ' .JText::_( 'OWNSERVICE_TRANSACTION_CORRECTED' );			
		}

		$mainframe->enqueueMessage($msg);	
		
		return $this->execute('failedtransactions');
	}

	/**
	 * Method to approve to transferrer
	 *
	 * @access public
	 * @return void
	 * @since 1.5
	 */
	function approve() {

		global $mainframe, $option;

		//Initialise variables
		$user		= &JFactory::getUser();
		$ownuser	= & Ownservice::getUser();

		//get vars
		$gid		= $user->gid;

		if($gid < 25) {
			$canApprove	= Ownservice::checkAccess('transaction', 'transfer', 'transaction', 'all');
			if (!$canApprove){
				JError::raiseWarning(500, JText::_('ALERTNOTAUTH') );
				$mainframe->redirect(JRoute::_('index.php?option=com_ownservice'));
			}
		}
		
		$cid = JRequest::getVar( 'cid', array(0), 'post', 'array' );

		if (!is_array( $cid ) || count( $cid ) < 1) {
			$msg = '';
			JError::raiseWarning(500, JText::_( 'OWNSERVICE_SELECT_REQUEST_APPROVAL_CORRECTED' ) );
		}

		$model = $this->getModel('Transactions');

		if(!$model->updateApprove($cid)){
			$msg = $model->getError();
		} else {
			$msg = count($cid) . ' ' . JText::_( 'OWNSERVICE_APPROVE' );
		}
		
		$mainframe->enqueueMessage($msg);

		return $this->execute('requestapprovalcorrected');
	}

	/**
	 * Logic to submit transaction to receiving transfer
	 *
	 * @access public
	 * @return void
	 * @since 1.5
	*/

	function transfer() {
		
		//Check for request forgeries
		JRequest::checkToken() or jexit('Invalid Token');
		
		global $mainframe, $option;

		//Initialise variables
		$user		= & JFactory::getUser();
		$ownuser	= & Ownservice::getUser();
		$db			= & JFactory::getDBO();
		
		//Set var
		$gid		= $user->gid;

		if($gid < 25) {
			$canTransfer= Ownservice::checkAccess('transaction', 'transfer', 'transaction', 'all');
			if (!$canTransfer) {
				JError::raiseWarning(500, JText::_('ALERTNOTAUTH') );
				$mainframe->redirect(JRoute::_('index.php?option=com_ownservice'));
			}
		}
		
		$cid		= JRequest::getVar( 'cid', array(), 'post', 'array' );
		$transferred= JRequest::getVar( 'transfer_id', 0, 'post', 'int' );
		
		if (!is_array( $cid ) || count( $cid ) < 1) {
			$msg = '';
			JError::raiseWarning(500, JText::_( 'OWNSERVICE_SELECT_REQUEST_APPROVAL' ) );
		}

		$model = $this->getModel('Transactions');
		
		if(!$model->updateTransferring($cid, $transferred)){
			$msg = $model->getError();
		} else {
			$msg = count($cid) . ' ' .JText::_( 'OWNSERVICE_APPROVAL_TRANSFERRED' );			
		}
		
		$mainframe->enqueueMessage($msg);

		return $this->execute('requestapproval');	
	}

	/**
	 * Logic to sumbit transfer success
	 *
	 * @access public
	 * @return void
	 * @since 1.5
	*/
	function success() {

		//Check for request forgeries
		JRequest::checkToken() or jexit('Invalid Token');

		global $mainframe;
		
		// Initialise variables
		$db			= & JFactory::getDBO();
		$app		= & JFactory::getApplication();
		$user		= & JFactory::getUser();
		$ownuser	= & Ownservice::getUser();

		//get vars
		$gid		= $user->gid;

		if($gid < 25) {
			$canTransferred	= Ownservice::checkAccess('transaction', 'transferred', 'transaction', 'all');
			if ( !$canTransferred ){
				JError::raiseWarning(500, JText::_('ALERTNOTAUTH') );
				$mainframe->redirect(JRoute::_('index.php?option=com_ownservice'));
			}
		}

		//set vars
		$cid		= JRequest::getVar( 'cid', array(0), 'post', 'array' );
		$comment	= JRequest::getVar( 'comment', array(0), 'post', 'array');
		
		if (!is_array( $cid ) || count( $cid ) < 1) {
			$msg = '';
			JError::raiseWarning(500, JText::_( 'OWNSERVICE_SELECT_ITEM_TRANSFER_SUCCESS' ) );
		}

		$model = $this->getModel('Transactions');
		
		if(!$model->updateSuccess($cid, $comment)){
			$msg = $model->getError();
		} else {
			$msg = count($cid) . ' ' . JText::_( 'OWNSERVICE_TRANSFER_SUCCESSFUL' );
		}

		$link = JRoute::_('index.php?option=com_ownservice&view=transactions');

		$this->setRedirect($link, $msg);
	}

	/**
	 * Logic to sumbit transfer fail
	 *
	 * @access public
	 * @return void
	 * @since 1.5
	*/
	function fail() {

		//Check for request forgeries
		JRequest::checkToken() or jexit('Invalid Token');

		global $mainframe;

		// Initialise variables
		$db			= & JFactory::getDBO();
		$app		= & JFactory::getApplication();
		$user		= & JFactory::getUser();
		$ownuser	= & Ownservice::getUser();
		$gid		= $user->gid;

		if($gid < 25) {
			$canTransferred	= Ownservice::checkAccess('transaction', 'transferred', 'transaction', 'all');
			if ( !$canTransferred ) {
				JError::raiseWarning(500, JText::_('ALERTNOTAUTH') );
				$mainframe->redirect(JRoute::_('index.php?option=com_ownservice'));
			}
		}

		$cid		= JRequest::getVar( 'cid', array(0), 'post', 'array' );
		$comment	= JRequest::getVar( 'comment', array(0), 'post', 'array' );

		if (!is_array( $cid ) || count( $cid ) < 1) {
			$msg = '';
			JError::raiseWarning(500, JText::_( 'OWNSERVICE_SELECT_ITEM_TRANSFER_FAIL' ) );
		}

		$model = $this->getModel('Transactions');

		if(!$model->updateFail($cid, $comment)){
			$msg =  $model->getError();	
		} else {
			$msg = count($cid) . ' ' . JText::_( 'OWNSERVICE_TRANSFER_FAILED' );
		}
		
		$link = JRoute::_('index.php?option=com_ownservice&view=transactions');

		$this->setRedirect($link, $msg);
	}

	/**
	 * Download logic transfer
	 *
	 * @access public
	 * @since 1.0
	 */
	function download() {

		global $mainframe;

		//Check for request forgeries
		JRequest::checkToken() or jexit('Invalid Token');

		// Initialise variables
		$user			= & JFactory::getUser();
		$ownuser	= & Ownservice::getUser();
		$gid			= $user->gid;
		$cid			= JRequest::getVar( 'cid', array(), 'post', 'array' );

		if($gid < 25) {
			$canTransferred	= Ownservice::checkAccess('transaction', 'transferred', 'transaction', 'all');
			if ( !$canTransferred ) {
				JError::raiseWarning(500, JText::_('ALERTNOTAUTH') );
				$mainframe->redirect(JRoute::_('index.php?option=com_ownservice'));
			}
		}

		//Get data form the model
		$model	= $this->getModel('Transactions');
		$rows	= $model->getTransferring($cid);
		
		require_once(JPATH_COMPONENT_SITE.DS.'classes'.DS.'PHPExcel.php');

		// Create new PHPExcel object
		$objPHPExcel = new PHPExcel();
		
		// Set properties
		$objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
							 ->setLastModifiedBy("Maarten Balliauw")
							 ->setTitle("Office 2007 XLSX Test Document")
							 ->setSubject("Office 2007 XLSX Test Document")
							 ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
							 ->setKeywords("office 2007 openxml php")
							 ->setCategory("Test result file");

		//Set default font
		$objPHPExcel->getActiveSheet()->getDefaultStyle()->getFont()->setName('Arial');
		$objPHPExcel->getActiveSheet()->getDefaultStyle()->getFont()->setSize(8);

		$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(15);
		$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(15);
		$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(15);
		$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(15);
		$objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(15);
		$objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(15);
		$objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(15);
		$objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(15);
		$objPHPExcel->getActiveSheet()->getColumnDimension('I')->setWidth(30);
		$objPHPExcel->getActiveSheet()->getColumnDimension('J')->setWidth(15);
		$objPHPExcel->getActiveSheet()->getColumnDimension('K')->setWidth(15);

		// Set row height
		$objPHPExcel->getActiveSheet()->getRowDimension(1)->setRowHeight(30);

		//Add Some data
		$objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', 'Account No.')
			->setCellValue('B1', 'Account Name')
			->setCellValue('C1', 'Account Type')
			->setCellValue('D1', 'Bank Name')
			->setCellValue('E1', 'Branch City')
			->setCellValue('F1', 'Phone No')
			->setCellValue('G1', 'Sender')
			->setCellValue('H1', 'Transfer Amount (AUD)')
			->setCellValue('I1', 'Rate')
			->setCellValue('J1', 'Total Receivable (THB)')
			->setCellValue('K1', 'Distributed Date');


		if( count($rows) >= 1 ) {
			$i = 2;
			$sumamount = 0;
			$sumtotal = 0;
			foreach($rows as $row) {
				$total = 0;
				if($row->extratotal > 0.00 ) {
					$total = $row->extratotal;
				} else {
					$total = (($row->amount * ($row->rate+$row->extrarate)) - ($row->bankfee+$row->extrabfee));
				}

				$sumamount = $sumamount + $row->amount;
				$sumtotal = $sumtotal + $total;
				
				$objPHPExcel->setActiveSheetIndex(0)
					->setCellValue('B'.$i, $row->account_name)
					->setCellValue('C'.$i, ucfirst($row->account_type))
					->setCellValue('D'.$i, ($row->bank_name=='other'?$row->bank_other:$row->bank_name))
					->setCellValue('E'.$i, $row->branch_city)
					->setCellValue('G'.$i, $row->username)
					->setCellValue('H'.$i, $row->amount)
					->setCellValue('I'.$i, ($row->rate+$row->extrarate))
					->setCellValue('J'.$i, $total)
					->setCellValue('K'.$i, date('d/m/Y', strtotime($row->requested_date)));
				
				$objPHPExcel->getActiveSheet()->getCell('F'.$i)->setValueExplicit($row->phone_no, PHPExcel_Cell_DataType::TYPE_STRING);
				$objPHPExcel->getActiveSheet()->getCell('A'.$i)->setValueExplicit($row->account, PHPExcel_Cell_DataType::TYPE_STRING);
				
				$objPHPExcel->getActiveSheet()->getStyle('H'.$i)->getNumberFormat()->setFormatCode("#,##0.00");
				$objPHPExcel->getActiveSheet()->getStyle('J'.$i)->getNumberFormat()->setFormatCode("#,##0.00");
				
				$i++;
			}

			//set sum
			$objPHPExcel->setActiveSheetIndex(0)->setCellValue('H'.($i+1), $sumamount);
			$objPHPExcel->setActiveSheetIndex(0)->setCellValue('J'.($i+1), $sumtotal);

			$objPHPExcel->getActiveSheet()->getStyle('H'.($i+1))->getNumberFormat()->setFormatCode("#,##0.00");
			$objPHPExcel->getActiveSheet()->getStyle('J'.($i+1))->getNumberFormat()->setFormatCode("#,##0.00");
		}

		// Freeze panes
		$objPHPExcel->getActiveSheet()->freezePane('A2');

		// Set style on cell
		$objPHPExcel->getActiveSheet()->getStyle('A1:K1')->applyFromArray(
			array(
				'alignment' => array(
				'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_LEFT,
				'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER,
				'wrap'=>true,
				)
			)
		);

		// Set active sheet index to the first sheet, so Excel opens this as the first sheet
		$objPHPExcel->setActiveSheetIndex(0);

		// Redirect output to a client’s web browser (Excel2007)
		//header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
		//header('Content-Disposition: attachment;filename="'.date('d-m-Y').'TRANSFER.xlsx"');
		//header('Cache-Control: max-age=0');

		//$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
		//$objWriter->save('php://output');
		// Redirect output to a client’s web browser (Excel5)
		header('Content-Type: application/vnd.ms-excel');
		header('Content-Disposition: attachment;filename="'.date('d-m-Y').'TRANSFER.xls"');
		header('Cache-Control: max-age=0');
		
		$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
		$objWriter->save('php://output');
		exit;
	}

	/**
	 * Download approval transferred
	 *
	 * @access public
	 * @return excel file
	 * @since 1.5
	 */
	 function downloadapprovaltransferred()
	{
		//Check for request forgeries
		JRequest::checkToken() or jexit('Invalid Token');

		// Initialise variables
		$user			= & JFactory::getUser();
		$ownuser	= & Ownservice::getUser();
		$gid			= $user->gid;

		$cid			= JRequest::getVar( 'cid', array(), 'post', 'array' );
		$transferred= JRequest::getVar( 'transfer_id', 0, 'post', 'int' );

		//Get data form the model
		$model		= $this->getModel('Transactions');
		$rows			= $model->getApprovalTransferred($cid);
		$transferrer	= $model->getTransferred($transferred);
		
		require_once(JPATH_COMPONENT_SITE.DS.'classes'.DS.'PHPExcel.php');

		// Create new PHPExcel object
		$objPHPExcel = new PHPExcel();
		
		// Set properties
		$objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
							 ->setLastModifiedBy("Maarten Balliauw")
							 ->setTitle("Office 2007 XLSX Test Document")
							 ->setSubject("Office 2007 XLSX Test Document")
							 ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
							 ->setKeywords("office 2007 openxml php")
							 ->setCategory("Test result file");

		//Set default font
		$objPHPExcel->getActiveSheet()->getDefaultStyle()->getFont()->setName('Arial');
		$objPHPExcel->getActiveSheet()->getDefaultStyle()->getFont()->setSize(8);

		$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(15);
		$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(15);
		$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(15);
		$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(15);
		$objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(15);
		$objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(15);
		$objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(15);
		$objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(30);
		$objPHPExcel->getActiveSheet()->getColumnDimension('I')->setWidth(15);
		$objPHPExcel->getActiveSheet()->getColumnDimension('J')->setWidth(30);

		// Set row height
		$objPHPExcel->getActiveSheet()->getRowDimension(1)->setRowHeight(30);

		//Add Some data
		$objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A2', 'Receipt No.')
			->setCellValue('B2', 'Member ID')
			->setCellValue('C2', 'Member Name')
			->setCellValue('D2', 'Receiver Name')
			->setCellValue('E2', 'Account No.')
			->setCellValue('F2', 'Bank Name')
			->setCellValue('G2', 'Branch City')
			->setCellValue('H2', 'Transfer Amount (AUD)')
			->setCellValue('I2', 'Rate')
			->setCellValue('J2', 'Total Receivable (THB)');

		$objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', 'Transferrer:');
		$objPHPExcel->setActiveSheetIndex(0)->setCellValue('D1', 'Requested Date:');

		$objPHPExcel->setActiveSheetIndex(0)->setCellValue('B1', $transferrer->name);
		$objPHPExcel->setActiveSheetIndex(0)->setCellValue('E1', date('d/m/Y'));

		if( count($rows) >= 1 ) 
		{
			$i = 3;
			$sumamount = 0;
			$sumtotal = 0;
			foreach($rows as $row) {
				$total = 0;
				if($row->extratotal > 0.00 ) {
					$total = $row->extratotal;
				} else {
					//$total = (($row->amount * ($row->rate+$row->extrarate)) - ($row->bankfee+$row->extrabfee));
					$total = (($row->iscore)?$row->total:$row->total_th);
				}
				
				$sumamount = $sumamount + $row->amount;
				$sumtotal = $sumtotal + $total;
				
				$objPHPExcel->setActiveSheetIndex(0)
					->setCellValue('A'.$i, $row->invoice)
					->setCellValue('B'.$i, $row->username)
					->setCellValue('C'.$i, $row->name)
					->setCellValue('D'.$i, $row->account_name)
					->setCellValue('F'.$i, ($row->bank_name=='other'?$row->bank_other:$row->bank_name))
					->setCellValue('G'.$i, $row->branch_city)
					->setCellValue('H'.$i,  $row->amount)
					->setCellValue('I'.$i, ($row->rate+$row->extrarate))
					->setCellValue('J'.$i, $total);
				
				$objPHPExcel->getActiveSheet()->getCell('E'.$i)->setValueExplicit($row->account, PHPExcel_Cell_DataType::TYPE_STRING);
				
				$objPHPExcel->getActiveSheet()->getStyle('H'.$i)->getNumberFormat()->setFormatCode("#,##0.00");
				$objPHPExcel->getActiveSheet()->getStyle('J'.$i)->getNumberFormat()->setFormatCode("#,##0.00");
				
				$i++;
			}
			
			//set sum
			$objPHPExcel->setActiveSheetIndex(0)->setCellValue('H'.($i+1), $sumamount);
			$objPHPExcel->setActiveSheetIndex(0)->setCellValue('J'.($i+1), $sumtotal);

			$objPHPExcel->getActiveSheet()->getStyle('H'.($i+1))->getNumberFormat()->setFormatCode("#,##0.00");
			$objPHPExcel->getActiveSheet()->getStyle('J'.($i+1))->getNumberFormat()->setFormatCode("#,##0.00");
		}

		$objPHPExcel->getActiveSheet()->mergeCells('B1:C1');
		$objPHPExcel->getActiveSheet()->mergeCells('E1:F1');

		// Freeze panes
		$objPHPExcel->getActiveSheet()->freezePane('A3');

		// Set style on cell
		$objPHPExcel->getActiveSheet()->getStyle('A2:J2')->applyFromArray(
			array(
				'alignment' => array(
				'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_LEFT,
				'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER,
				'wrap'=>true,
				)
			)
		);

		// Set active sheet index to the first sheet, so Excel opens this as the first sheet
		$objPHPExcel->setActiveSheetIndex(0);

		// Redirect output to a client’s web browser (Excel2007)
		//header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
		//header('Content-Disposition: attachment;filename="'.date('d-m-Y').'TRANSFER.xlsx"');
		//header('Cache-Control: max-age=0');

		//$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
		//$objWriter->save('php://output');
		// Redirect output to a client’s web browser (Excel5)
		header('Content-Type: application/vnd.ms-excel');
		header('Content-Disposition: attachment;filename="'.date('d-m-Y').'APPROVALTRANSFERRED.xls"');
		header('Cache-Control: max-age=0');
		
		$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
		$objWriter->save('php://output');

		exit();
	 }

	/**
	 * Method to fetch the members form
	 * 
	 * @since 1.5
	 */
	function viewmembers()
	{
		// Check for request forgeries
		JRequest::checkToken('request') or jexit( 'Invalid Token' );

		$user =&JFactory::getUser();

		//header('Content-type: application/json');
		@ob_end_clean();
		header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
		header("Cache-Control: no-cache");
		header("Pragma: no-cache");
		//header("Content-type:text/json");

		$model 			=  $this->getModel('Transaction');
		$memberobjs 	=  $model->getmembers(JRequest::getVar('q'));
		$array = array();
		echo "[";
		foreach($memberobjs as $member) {
			$array[] = "{\"id\":\"".$member->id."\",\"name\":\"".$member->username.' '.$member->name."\"}";
		}
		echo implode(",", $array);
		echo "]";
		exit;
	}

	/**
	 * Method to get Image of Member
	 * 
	 * @access public
	 * @return string
	 * @since 1.5
	 */
	 function getImage()
	 {
	 	// Check for request forgeries
		JRequest::checkToken('request') or jexit( 'Invalid Token' );

		$id  = JRequest::getVar('id', 0 , 'post', 'int');

		$model 			=  $this->getModel('Transaction');
		
		$image 			=  $model->getImage($id);
		
		//resize image
		$path	= OwnserviceHelper::getParams('path', 'images/stories/ownservices');
		$info 	= @getimagesize(JPATH_SITE.DS.$path.DS.$image->userid.DS.$image->filename);
		if (($info[0] > 200) || ($info[1] > 200)) {
			$dimensions		= OwnserviceHelper::imageResize($info[0], $info[1], 200);
			$image->width	= $dimensions[0];
			$image->height	= $dimensions[1];
		} else {
			$image->width	= $info[0];
			$image->width	= $info[1];
		}
		if($image->filename){
			echo '<a class="img-preview" href="'.JURI::root(true).'/'.OwnserviceHelper::getParams('path', 'images/stories/ownservices').'/'.$id.'/'.$image->filename.'">';
				echo '<img src="'.JURI::root(true).'/'.OwnserviceHelper::getParams('path', 'images/stories/ownservices').'/'.$id.'/'.$image->filename.'" style="border: 0; width:'.$image->width.'px; height:'.$image->height.'px;" />';
			echo '</a>';
		}
		exit;
	 }

	/**
	 * Method to check expire of user
	 * 
	 * @access public
	 * @return json string
	 * @since 1.5
	 */
	 function checkexpire()
	 {
	 	// Check for request forgeries
		JRequest::checkToken('request') or jexit( 'Invalid Token' );

		$id  	= JRequest::getVar('id', 0 , 'post', 'int');
		
		$model 	=  $this->getModel('Transaction');
		
		$user	= $model->getUser($id);
		
		$curentdate	= mktime(0, 0, 0, date('m'), date('d'), date('Y'));
		list($edy, $edm, $edd)	= explode('-', $user->expire_date);
		$expiredate = mktime(0, 0, 0, $edm, $edd, $edy);
		
		$days = ($expiredate - $curentdate) / 86400;		
		
		//header('Content-type: application/json');
		@ob_end_clean();
		header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
		header("Cache-Control: no-cache");
		header("Pragma: no-cache");
		//header("Content-type:text/json");
		
		echo "{\"days\":\"".$days."\", \"expiredate\":\"".$user->expire_date."\",\"id\":\"".$user->id."\", \"fileid\":\"".$user->fileid."\"}";
		exit();
	 }

	 /**
	  * Method to checked sender get transfer
	  *
	  * @return json
	  */
	 function ajaxcheckmaxlastsendertransfer()
	{
		// Check for request forgeries
		JRequest::checkToken('request') or jexit( 'Invalid Token' );

		//Initialise variables
		$db		= & JFactory::getDBO();

		//Get var
		$id		= JRequest::getVar('id', 0, 'post', 'int');
		$value	= JRequest::getVar('value', 0, 'post');
		$days	= JRequest::getVar('days', 30, 'post');

		// check 10 days
		$query	= 'SELECT SUM(amount) FROM #__ownservice_transactions'
						.' WHERE curdate() < date_add(requested_date,interval '.$days.' day)'
						.' AND state=4'
						.' AND user_id='.$id
						;
		$db->setQuery($query);
		$sum = $db->loadResult();

		$day = 10;
		$sum = ($sum+$value);
		
		// check 30 days
		if($sum < 10000)
		{
			$query	= 'SELECT SUM(amount) FROM #__ownservice_transactions'
							.' WHERE curdate() < date_add(requested_date,interval 30 day)'
							.' AND state=4'
							.' AND user_id='.$id
							;
			$db->setQuery($query);
			$sum = $db->loadResult();

			$day = 30;
			$sum = ($sum+$value);
		}

		$over_transfer = $sum >= 10000?1:0;

		//header('Content-type: application/json');
		@ob_end_clean();
		header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
		header("Cache-Control: no-cache");
		header("Pragma: no-cache");
		//header("Content-type:text/json");

		echo '{"over":"'.$over_transfer.'", "overday":"'.$day.'"}';

		 exit();
	 }

	 /**
	  * Method to checked receiver get transfer
	  *
	  * @return json
	  */
	 function ajaxcheckmaxlastreceivertransfer()
	 {
		// Check for request forgeries
		JRequest::checkToken('request') or jexit( 'Invalid Token' );

		//Initialise variables
		$db		= & JFactory::getDBO();

		//Get var
		$id			= JRequest::getVar('id', 0, 'post');
		$days 		= JRequest::getVar('days', 30, 'post');
		$account	= JRequest::getVar('account', 0, 'post');
		$amount		= JRequest::getVar('value', 0, 'post');

		if($account == '') $account = 'null';
		//Get account name
		$query		= 'SELECT account_name FROM #__ownservice_accounts WHERE account_no='.$db->Quote($account);
		$db->setQuery($query);
		$accountname= $db->loadResult();

		// check amount over on 10 days
		$query	= ' SELECT distinct t.id, t.amount FROM #__ownservice_transactions AS t '
					.' LEFT JOIN #__ownservice_accounts AS a ON a.account_no=t.account '
					.' WHERE curdate() < date_add(t.requested_date,interval '.$days.' day)'
					.' AND t.state=4 '
					.' AND ( a.account_no='.$db->Quote($account).' OR a.account_name='.$db->Quote($accountname).')'
					;

		$db->setQuery($query);
		$rows = $db->loadObjectList();

		$sum = 0;
		if($rows) {
			foreach($rows as $row) {
				$sum = $sum + $row->amount;
			}
		}
		$day = 10;
		$sum = ($sum+$amount);

		// check amount over on 30 days
		if($sum < 10000)
		{
			$query	= ' SELECT distinct t.id, t.amount FROM #__ownservice_transactions AS t '
						.' LEFT JOIN #__ownservice_accounts AS a ON a.account_no=t.account '
						.' WHERE curdate() < date_add(t.requested_date,interval 30 day)'
						.' AND t.state=4 '
						.' AND ( a.account_no='.$db->Quote($account).' OR a.account_name='.$db->Quote($accountname).')'
						;

			$db->setQuery($query);
			$rows = $db->loadObjectList();

			$sum = 0;

			if($rows) {
				foreach($rows as $row) {
					$sum = $sum + $row->amount;
				}
			}

			$day = 30;
			$sum = ($sum+$amount);
		}
		
		$over_transfer = $sum >= 10000?1:0;

		//header('Content-type: application/json');
		@ob_end_clean();
		header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
		header("Cache-Control: no-cache");
		header("Pragma: no-cache");
		//header("Content-type:text/json");

		echo '{"over":"'.$over_transfer.'","overday":"'.$day.'"}';

		exit();
	 }

	/**
	  * Method to get last sender transfer
	  *
	  * @return html
	  */
	 function ajaxgetmaxlastsendertransfer()
	{
		 // Check for request forgeries
		JRequest::checkToken('request') or jexit( 'Invalid Token' );
		
		//Initialise variables
		$db		= & JFactory::getDBO();

		//Get var
		$id				= JRequest::getVar('id', 0, 'post', 'int');
		$days 			= JRequest::getVar('days', 30, 'post');
		$dateformat  	= OwnserviceHelper::getParams('date_format', '%d/%m/%Y'); 
		$priceformat 	= OwnserviceHelper::getParams('price_format', '#,###.##');

		$query	= ' SELECT t.*, a.account_name FROM #__ownservice_transactions AS t '
						.' LEFT JOIN #__ownservice_accounts AS a ON a.account_no = t.account '
						.' WHERE curdate() < date_add(t.requested_date,interval '.$days.' day)'
						.' AND t.state=4'
						.' AND t.user_id='.$id
						.' GROUP BY t.id '
						.' ORDER BY t.created'
						;
		$db->setQuery($query);
		$rows = $db->loadObjectList();
		
		$sumamount = 0;

		$html ='<div id="ownservices">';
		if($days == 30)
		{
			$html .='<p>Total Transfer amount is over $10,000 within '.$days.' days.</p>';
		}
		if($days == 10)
		{
			$html .='<p>Total Transfer amount is over $10,000 within '.$days.' days. <span style="background-color: yellow;">Please complete LPMT form!</span></p>';
		}
		$html .= '<table cellspacing="1" class="adminlist">';
		$html .='<tr>';
			$html .='<td align="center" class="tablelist">#</td>';
			$html .='<td align="center" class="tablelist">'.JText::_('OWNSERVICE_ACCOUNT_NO').'</td>';
			$html .='<td align="center" class="tablelist">'.JText::_('OWNSERVICE_ACCOUNT_NAME').'</td>';
			$html .='<td align="center" class="tablelist">'.JText::_('OWNSERVICE_CREATE_DATE').'</td>';
			$html .='<td align="center" class="tablelist">'.JText::_('OWNSERVICE_AMOUNT').'<br /> (AUD)</td>';
		$html .='</tr>';
		if($rows) {
			foreach($rows as $i=>$row) {
				$sumamount = $sumamount+$row->amount;
				$html .='<tr class="row'.($i % 2).'">';
					$html .='<td align="center" class="inner_tablelist">'.($i+1).'</td>';
					$html .='<td align="center" class="inner_tablelist">'.$row->account.'</td>';
					$html .='<td align="center" class="inner_tablelist">'.$row->account_name.'</td>';
					$html .='<td align="center" class="inner_tablelist">'.JHTML::_('date', $row->created, $dateformat).'</td>';
					$html .='<td align="center" class="inner_tablelist">'.OwnserviceHelper::moneyFormat($priceformat, $row->amount).'</td>';
				$html .='</tr>';
			}
		}
		$html .='<tr>';
			$html .='<td colspan="4" align="right">'.JText::_('OWNSERVICE_TOTAL').'</td>';
			$html .='<td align="center" class="inner_tablelist"><span style="color:red;font-weight: bold;">'.OwnserviceHelper::moneyFormat($priceformat, $sumamount).'</span></td>';
		$html .='</tr>';
		$html .='</table>';
		$html .='</div>';

		echo $html;
		exit();
	 }

	 /**
	  * Method to get last receiver transfer
	  *
	  * @return html
	  */
	 function ajaxgetlastreceivertransfer()
	 {
		 // Check for request forgeries
		JRequest::checkToken('request') or jexit( 'Invalid Token' );
		
		//Initialise variables
		$db		= & JFactory::getDBO();

		//Get var
		$account		= JRequest::getVar('account', 0, 'post');
		$days 			= JRequest::getVar('days', 30, 'post');
		$dateformat  	= OwnserviceHelper::getParams('date_format', '%d/%m/%Y'); 
		$priceformat 	= OwnserviceHelper::getParams('price_format', '#,###.##');

		//Get account name
		$query	= 'SELECT account_name FROM #__ownservice_accounts WHERE account_no='.$db->Quote($account);
		$db->setQuery($query);
		$accountname = $db->loadResult();

		//Get data
		$query	= ' SELECT t.*, a.account_name FROM #__ownservice_transactions AS t '
						.' LEFT JOIN #__ownservice_accounts AS a ON a.account_no = t.account '
						.' WHERE curdate() < date_add(t.requested_date,interval '.$days.' day)'
						.' AND t.state=4'
						.' AND ( a.account_no='.$db->Quote($account).' OR a.account_name='.$db->Quote($accountname).')'
						.' GROUP BY t.id '
						.' ORDER BY t.created'
						;
		$db->setQuery($query);
		$rows = $db->loadObjectList();
		
		$sumamount = 0;

		$html ='<div id="ownservices">';
		if($days == 30)
		{
			$html .='<p>This receiver account total transfer amount is over $10,000 within '.$days.' days.</p>';
		}
		if($days == 10)
		{
			$html .='<p>This receiver account total transfer amount is over $10,000 within '.$days.' days. <span style="background-color: yellow;">Please complete LPMT form!</span></p>';
		}
		$html .='<table cellspacing="1" class="adminlist">';
		$html .='<tr>';
			$html .='<td align="center" class="tablelist">#</td>';
			$html .='<td align="center" class="tablelist">'.JText::_('OWNSERVICE_ACCOUNT_NO').'</td>';
			$html .='<td align="center" class="tablelist">'.JText::_('OWNSERVICE_ACCOUNT_NAME').'</td>';
			$html .='<td align="center" class="tablelist">'.JText::_('OWNSERVICE_CREATE_DATE').'</td>';
			$html .='<td align="center" class="tablelist">'.JText::_('OWNSERVICE_AMOUNT').'<br /> (AUD)</td>';
		$html .='</tr>';
		if($rows) {
			foreach($rows as $i=>$row) {
				$sumamount = $sumamount+$row->amount;
				$html .='<tr class="row'.($i % 2).'">';
					$html .='<td align="center" class="inner_tablelist">'.($i+1).'</td>';
					$html .='<td align="center" class="inner_tablelist">'.$row->account.'</td>';
					$html .='<td align="center" class="inner_tablelist">'.$row->account_name.'</td>';
					$html .='<td align="center" class="inner_tablelist">'.JHTML::_('date', $row->created, $dateformat).'</td>';
					$html .='<td align="center" class="inner_tablelist">'.OwnserviceHelper::moneyFormat($priceformat, $row->amount).'</td>';
				$html .='</tr>';
			}
		}
		$html .='<tr>';
			$html .='<td colspan="4" align="right">'.JText::_('OWNSERVICE_TOTAL').'</td>';
			$html .='<td align="center" class="inner_tablelist"><span style="color:red;font-weight: bold;">'.OwnserviceHelper::moneyFormat($priceformat, $sumamount).'</span></td>';
		$html .='</tr>';
		$html .='</table>';
		$html .='</div>';

		echo $html;
		exit();
	 }

	 function ajaxgetlastsendertransfer() {

		// Check for request forgeries
		JRequest::checkToken('request') or jexit( 'Invalid Token' );
		
		//Initialise variables
		$db		= & JFactory::getDBO();

		//Get var
		$id					= JRequest::getVar('id', 0, 'post', 'int');
		$dateformat  	= OwnserviceHelper::getParams('date_format', '%d/%m/%Y'); 
		$priceformat 	= OwnserviceHelper::getParams('price_format', '#,###.##');

		$query = ' SELECT t.*, a.bank_name, a.bank_other, a.branch_city, c.iscore, c.code AS currencycode '
					.' FROM #__ownservice_transactions AS t '
					.' LEFT JOIN #__ownservice_accounts AS a ON a.account_no = t.account '
					.' LEFT JOIN #__ownservice_exchangerates AS e ON e.id=t.rate_id '
					.' LEFT JOIN #__ownservice_currencies AS c ON c.id=e.currency_id '
					.' WHERE t.state=4 '
					.' AND t.user_id='.$id
					.' GROUP BY t.id '
					.' ORDER By t.requested_date DESC'
					.' LIMIT 0, 10'
				;
		
		$db->setQuery($query);
		$rows = $db->loadObjectList();

		$sumamount = 0;
		$sumtotal = 0;

		$html ='<h3>Last 10 Transaction</legend></h3>';
		$html .= '<table cellspacing="1" class="adminlist">';
		$html .='<tr>';
			$html .='<td align="center" class="tablelist"></td>';
			$html .='<td align="center" class="tablelist">'.JText::_('OWNSERVICE_RECEIVER_NO').'</td>';
			$html .='<td align="center" class="tablelist">'.JText::_('OWNSERVICE_ACCOUNT_NO').'</td>';
			$html .='<td align="center" class="tablelist">'.JText::_('OWNSERVICE_BANK_NAME').'</td>';
			$html .='<td align="center" class="tablelist">'.JText::_('OWNSERVICE_BRANCH_CITY').'</td>';
			$html .='<td align="center" class="tablelist">'.JText::_('OWNSERVICE_TRANSFER_ON').'</td>';
			$html .='<td align="center" class="tablelist">'.JText::_('OWNSERVICE_AMOUNT_TRANSFER').'<br />(AUD)</td>';
			$html .='<td align="center" class="tablelist">'.JText::_('OWNSERVICE_RATE').'</td>';
			$html .='<td align="center" class="tablelist">'.JText::_('OWNSERVICE_TOTAL_EXCHANGE').'</td>';
		$html .='</tr>';
		if($rows) {
			foreach($rows as $i=>$row) {
				$sumamount = $sumamount +  $row->amount;
				$html .='<tr class="row'.($i % 2).'">';
					$html .='<td align="center" class="inner_tablelist">'.($i+1).'</td>';
					$html .='<td align="center" class="inner_tablelist"><a href="'.JRoute::_('index.php?option=com_ownservice&controller=transaction&task=detail&id='.$row->id).'">'.$row->invoice.'</a></td>';
					$html .='<td align="center" class="inner_tablelist">'.OwnserviceHelper::accountFormat($row->account).'</td>';
					$html .='<td align="center" class="inner_tablelist">'.($row->bank_name=='other'?$row->bank_other:$row->bank_name).'</td>';
					$html .='<td align="center" class="inner_tablelist">'.$row->branch_city.'</td>';
					$html .='<td align="center" class="inner_tablelist">'.JHTML::_('date', $row->requested_date, $dateformat).'</td>';
					$html .='<td align="center" class="inner_tablelist">'.OwnserviceHelper::moneyFormat($priceformat,$row->amount).'</td>';
					$html .='<td align="center" class="inner_tablelist">';
							$color = '';
							if($row->extrarate > 0.00 ) {
								$color = 'red';
							} else if($row->extrarate < 0.00) {
								$color = 'green';
							}

							if(!$row->iscore) {
								$html .='<div style="border-bottom: 1px dotted #ccc;">'.OwnserviceHelper::moneyFormat($priceformat,$row->rate_th).' THB</div>';
							} else {
								$html .='<div class ="'.$color.'">'.OwnserviceHelper::moneyFormat($priceformat,$row->rate+$row->extrarate).' '.$row->rate_code.'</div>';
							}

					$html .='</td>';
					$html .='<td align="center" class="inner_tablelist">';
							if(!$row->iscore) {
								$html .='<div style="border-bottom: 1px dotted #ccc;">'.OwnserviceHelper::moneyFormat($priceformat,$row->total_th).' THB</div>';
							}
							$html .='<div class="'.($row->extratotal > 0.00?'red':'').'">';
								if($row->extratotal > 0.00) {
									$html .=OwnserviceHelper::moneyFormat($priceformat, $row->extratotal).' '.$row->rate_code;
									$sumtotal  = $sumtotal + $row->extratotal;
								} else {
									$html .=OwnserviceHelper::moneyFormat($priceformat,( ($row->amount * ($row->rate+$row->extrarate)) - ($row->bankfee+$row->extrabfee))).' '.$row->rate_code;
									$sumtotal  = $sumtotal + ($row->amount * ($row->rate+$row->extrarate));
								}
							$html .='</div>';
					$html .='</td>';
				$html .='</tr>';
			}
		}
		$html .='<tr>';
			$html .='<td colspan="6" align="right" class="inner_tablelist">'.JText::_('OWNSERVICE_TOTAL').' </td>';
			$html .='<td align="center" class="inner_tablelist">'.OwnserviceHelper::moneyFormat($priceformat, $sumamount).'</td>';
			$html .='<td>'.'</td>';
			$html .='<td align="center" class="inner_tablelist">'.OwnserviceHelper::moneyFormat($priceformat, $sumtotal).'</td>';
		$html .='</tr>';
		$html .='</table>';

		echo $html;
		exit();
	 }
	 
	 /**
	  * Method to get transaction cancelled detail
	  * 
	  * @return void
	  * @since 1.0
	  */
	  function detailcancelled()
	  {
	  	global $mainframe;

		// Initialise variables
		$user		= & JFactory::getUser();
		$ownuser	= & Ownservice::getUser();

		$id 		= JRequest::getVar('id');
		
		if($user->gid < 25) {
			$canView	= Ownservice::checkAccess('transaction', 'view', 'transaction', 'all');
			if (!$canView) {
				JError::raiseWarning(500, JText::_('ALERTNOTAUTH') );
				$mainframe->redirect(JRoute::_('index.php?option=com_ownservice'));
			}
		}

		// Create the view
		$view = & $this->getView('transaction', 'html');

		// Get/Create the model
		$model = & $this->getModel('Transaction');
		
		//update read cancelled
		$model->readCancelled($id);
		
		// Push the model into the view (as default)
		$view->setModel($model, true);

		// Set the layout
		$view->setLayout('detailcancelled');

		// Display the view
		$view->display();
	  }
	  
	 /**
	 * Logic to set transfer cancelled
	 *
	 * @access public
	 * @return void
	 * @since 1.5
	*/
	function cancelled() {

		//Check for request forgeries
		JRequest::checkToken() or jexit('Invalid Token');

		global $mainframe;
		
		// Initialise variables
		$db			= & JFactory::getDBO();
		$app		= & JFactory::getApplication();
		$user		= & JFactory::getUser();
		$ownuser	= & Ownservice::getUser();

		//get vars
		$gid		= $user->gid;

		if($gid < 25) {
			$manage = Ownservice::checkAccess( 'transaction', 'manage' );
			if ( !$manage ){
				JError::raiseWarning(500, JText::_('ALERTNOTAUTH') );
				$mainframe->redirect(JRoute::_('index.php?option=com_ownservice'));
			}
		}

		//set vars
		$id		= JRequest::getVar( 'id', 0, 'post', 'int' );
	
		$model = $this->getModel('Transactions');
		
		if(!$model->updateCancelled($id)){
			$msg = $model->getError();
		} else {
			$msg = JText::_( 'OWNSERVICE_TRANSACTION_CANCELLED' );
		}

		$link = JRoute::_('index.php?option=com_ownservice&view=transactions');

		$this->setRedirect($link, $msg);
	}

	/**
	* Approval the transaction of customer
	*/
	function customerapprove()
	{
		//Check for request forgeries
		JRequest::checkToken() or jexit('Invalid Token');

		global $mainframe;

		//Initialise variables
		$user		= & JFactory::getUser();
		$ownuser	= & Ownservice::getUser();

		//get vars
		$gid		= $user->gid;

		if($gid < 25) 
		{
			$canCustomerTransfers= Ownservice::checkAccess('transaction', 'customer', 'transaction', 'all');
			if ( !$canCustomerTransfers )
			{
				JError::raiseWarning(500, JText::_('ALERTNOTAUTH') );
				$mainframe->redirect(JRoute::_('index.php?option=com_ownservice'));
			}
		}

		//get vars
		$option		= JRequest::getCmd( 'option' );
		$cid		= JRequest::getVar( 'cid', 0, 'post', 'array' );
		$msg		= null;
		$msgType	= 'message';

		JArrayHelper::toInteger($cid);
		
		if (count($cid) < 1) {
			$msg =  JText::_('Select an item to delete');
			$mainframe->redirect('index.php?option='.$option, $msg, 'error');
		}

		//Get the model
		$model = &$this->getModel('Transaction');

		if($model->customerapprove($cid)) 
		{
			$msg		= JText::sprintf('OWNSERVICE_SUBMIT_CUSTOMER_TRANSFERS', count($cid));		
		}
		else
		{
			$msg		= $model->getError();
			$msgType	= 'error';
		}

		$mainframe->redirect('index.php?option='.$option.'&controller=transaction&task=customertransfers', $msg, $msgType);
	}

	/**
	 * Edit the transaction of customer
	*/
	function customeredit()
	{
		//Check for request forgeries
		JRequest::checkToken() or jexit('Invalid Token');

		global $mainframe;

		//Initialise variables
		$user		= & JFactory::getUser();
		$ownuser	= & Ownservice::getUser();

		//get vars
		$gid		= $user->gid;

		if($gid < 25) 
		{
			$canCustomerTransfers= Ownservice::checkAccess('transaction', 'customer', 'transaction', 'all');
			if ( !$canCustomerTransfers )
			{
				JError::raiseWarning(500, JText::_('ALERTNOTAUTH') );
				$mainframe->redirect(JRoute::_('index.php?option=com_ownservice'));
			}
		}

		// Create the view
		$view = & $this->getView('transaction', 'html');

		// Get/Create the model
		$model = & $this->getModel('Transaction');

		// Push the model into the view (as default)
		$view->setModel($model, true);

		// Set the layout
		$view->setLayout('customerform');

		// Display the view
		$view->display();

	}

	/**
	 * Delete the transaction of cuistomer
	*/
	function customerdelete()
	{
		//Check for request forgeries
		JRequest::checkToken() or jexit('Invalid Token');

		global $mainframe;

		//Initialise variables
		$user		= & JFactory::getUser();
		$ownuser	= & Ownservice::getUser();

		//set vars
		$gid		= $user->gid;

		if($gid < 25) 
		{
			$canCustomerTransfers= Ownservice::checkAccess('transaction', 'customer', 'transaction', 'all');
			if ( !$canCustomerTransfers )
			{
				JError::raiseWarning(500, JText::_('ALERTNOTAUTH') );
				$mainframe->redirect(JRoute::_('index.php?option=com_ownservice'));
			}
		}

		//get vars
		$option		= JRequest::getCmd( 'option' );
		$cid		= JRequest::getVar( 'cid', 0, 'post', 'array' );
		$msg		= null;
		$msgType	= 'message';

		JArrayHelper::toInteger($cid);
		
		if (count($cid) < 1) {
			$msg =  JText::_('Select an item to delete');
			$mainframe->redirect('index.php?option='.$option, $msg, 'error');
		}

		//Get the model
		$model = &$this->getModel('Transaction');

		if($model->customerdelete($cid)) 
		{
			$msg		= JText::sprintf('OWNSERVICE_DELETE_CUSTOMER_TRANSFERS', count($cid));		
		}
		else
		{
			$msg		= $model->getError();
			$msgType	= 'error';
		}

		$mainframe->redirect('index.php?option='.$option.'&controller=transaction&task=customertransfers', $msg, $msgType);	

	}

	function customertransfersave()
	{
		// Check for request forgeries
		JRequest::checkToken() or jexit( 'Invalid Token' );

		$option	=& JRequest::getCmd( 'option' );
		$user 	=& JFactory::getUser();
		$app 	=& JFactory::getApplication();

		// Get vars
		$post 	= JRequest::get( 'post' );
		$msg 	= '';
		$type 	= 'message';

		// Get data from the model
		$model = $this->getModel('Transaction');

		if($model->customertransfersave($post)){
			$msg = JText::_('OWNSERVICE_CUSTOMER_TRANSFER_SAVED');
		} else {
			$type = 'error';
			$msg = JText::_('OWNSERVICE_ERROR_SAVING_CUSTOMER_TRANSFER');
		}

		$link = JRoute::_('index.php?option='.$option.'&controller=transaction&task=customertransfers');
		
		$this->setRedirect($link, $msg, $type);
	}

	function customertransfercancel()
	{
		// Check for request forgeries
		JRequest::checkToken() or jexit( 'Invalid Token' );
			
		$link = JRoute::_('index.php?option=com_ownservice&controller=transaction&task=customertransfers');

		$this->setRedirect( $link );
	}
}